package com.cuitrip.business.pay.presenter;

import android.text.TextUtils;

import com.cuitrip.apiservice.OrderBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.app.base.CtException;
import com.cuitrip.app.base.CtFetchCallback;
import com.cuitrip.business.order.model.OrderItem;
import com.cuitrip.business.pay.CreditCardPayActivity;
import com.cuitrip.business.pay.model.DiscountItem;
import com.cuitrip.business.pay.model.PayMode;
import com.cuitrip.business.pay.ui.IPayOrderView;
import com.cuitrip.service.R;
import com.cuitrip.util.NetworkUtil;
import com.cuitrip.util.ResourceUtil;
import com.cuitrip.util.track.TrackUtil;
import com.lab.mvp.presenter.Presenter;
import com.lab.network.config.CtResponseCode;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.utils.MessageUtils;
import com.lab.utils.Utils;

import java.util.ArrayList;


/**
 * Created by sheena on 16/2/18.
 */
public class PayDetailPresenter implements Presenter<IPayOrderView>,IProxyCallback{

    public static final int VISA=1;
    public static final int MASTERCARD=2;
    public static final String  PAY_CHANEL_VISA="visa";
    public static final String PAY_CHANEL_MASTERCARD="mc";
    public static final String PAY_CHANEL_ALIPAY = "alipay";
    public static final String PAY_CHANEL_WXPAY = "wx";
    IPayOrderView mPayOrderView;
    private String oid;
    private ApiProxy mApiProxy = new ApiProxy(this);
    private OrderItem orderItem;
    private DiscountItem discountItem;
    private boolean isInitial=true;

    @Override
    public void attachView(IPayOrderView view) {
        mPayOrderView =view;
    }

    public void loadPayOrderMode(String oid){
        mPayOrderView.displayLoading();
        this.oid=oid;
        OrderBusiness.getOrderInfo(mApiProxy, oid);
    }

    public void selectDiscount(DiscountItem discountItem,int checkedPosition){
        String payChannel = getPayChannel(checkedPosition);
        if(discountItem !=null) {
            this.discountItem = discountItem;
            OrderBusiness.getFinalPrice(mApiProxy, oid, orderItem.getPayCurrency(), payChannel,discountItem.getCode());
        }else{
            OrderBusiness.getFinalPrice(mApiProxy, oid, orderItem.getPayCurrency(), payChannel,"");

        }
        mPayOrderView.renderCouponInfo(discountItem);

    }
    private String getPayChannel(int checkedPosition){
        String payCurrency = orderItem.getPayCurrency().toUpperCase();
        switch (checkedPosition){
            /**
             * 人民币支付，第一个item是支付宝支付
             * 外币支付，第一个item是visa支付
             */
            case 0:
                if ("CNY".equals(payCurrency)) {
                    return PAY_CHANEL_ALIPAY;
                } else {
                    return PAY_CHANEL_VISA;
                }

            /**
             * 人民币支付 && 微信安装，第二个item是微信支付
             * 人民币支付 && 微信未安装，第二个item是visa支付
             * 外币支付，第二个item是MasterCard支付
             */
            case 1:
                if ("CNY".equals(orderItem.getPayCurrency().toUpperCase()) && Utils.isWXInstalled()) {
                    return PAY_CHANEL_WXPAY;
                } else if ("CNY".equals(orderItem.getPayCurrency().toUpperCase()) && (!Utils.isWXInstalled())) {
                    return PAY_CHANEL_VISA;
                } else {
                    return PAY_CHANEL_MASTERCARD;
                }

            /**
             * 人民币支付 && 微信安装，第三个item是visa支付
             * 人民币支付 && 微信未安装，第三个item是MasterCard支付
             */
            case 2:
                if (Utils.isWXInstalled()) {
                    return PAY_CHANEL_VISA;
                } else {
                    return PAY_CHANEL_MASTERCARD;
                }

            /**
             * 第四个item只可能是MasterCard支付
             */
            case 3:
                return PAY_CHANEL_MASTERCARD;
        }
        return null;
    }

    public void clickPay(String finalPrice,int type,String couponId){
        if ("0.00".equals(finalPrice)){
            payWithPing(PAY_CHANEL_ALIPAY, "0.00".equals(finalPrice), couponId);
            return;
        }
        String payChannel = getPayChannel(type);
        if (payChannel.equals(PAY_CHANEL_ALIPAY)){
            payWithPing(PAY_CHANEL_ALIPAY, "0.00".equals(finalPrice), couponId);
        }else if (payChannel.equals(PAY_CHANEL_WXPAY)){
            payWithPing(PAY_CHANEL_WXPAY,"0.00".equals(finalPrice),couponId);
        }else if (payChannel.equals(PAY_CHANEL_VISA)){
            payWithAdyen(VISA,finalPrice,couponId);
        }else if(payChannel.equals(PAY_CHANEL_MASTERCARD)){
            payWithAdyen(MASTERCARD,finalPrice,couponId);
        }

    }
    public void getChar(String oid, String type, String ip, String currency, String couponId, final CtFetchCallback<String> callback) {
        ApiProxy orderChargeProxy = new ApiProxy(new IProxyCallback() {
            @Override
            public boolean onProxyResult(ProxyResult<?> result) {
                CtApiResponse response = (CtApiResponse) result.getData();
                if (response.isResponseNormal()) {
                    callback.onSuc(String.valueOf(response.result));
                } else {
                    String msg = response.msg;
                    if (TextUtils.isEmpty(msg)) {
                        msg = ResourceUtil.getString(R.string.pay_operation_pay_feedback_fail);
                    }
                    callback.onFailed(new CtException(msg));
                }
                return false;
            }
        });
        //获取订单支付详情
        OrderBusiness.getCharge(orderChargeProxy, oid, type, ip, currency, couponId);
    }


    public void payWithPing(String method, final boolean noNeedPay,String couponId) {
        getChar(oid, method, NetworkUtil.getIPAddress(), orderItem.getPayCurrency(), couponId, new CtFetchCallback<String>() {
            @Override
            public void onSuc(String s) {
                if (noNeedPay) {
                    mPayOrderView.uiPaySuc();
                } else {
                    mPayOrderView.requestPay(s);
                }
            }

            @Override
            public void onFailed(CtException throwable) {
                MessageUtils.showToast(throwable.getMessage());
            }
        });
    }

    public void payWithAdyen(int type,String finalPrice,String couponId){
        switch (type){
            case VISA:
                TrackUtil.trackScreenName("/pay/visa");
                CreditCardPayActivity.startActivity(mPayOrderView.getContext(),VISA,finalPrice,orderItem,couponId);
                break;

            case MASTERCARD:
                TrackUtil.trackScreenName("/pay/mastercard");
                CreditCardPayActivity.startActivity(mPayOrderView.getContext(), MASTERCARD, finalPrice, orderItem, couponId);
                break;
        }
    }

    private void handResponse(CtApiResponse response){
        if (response != null && response.code == CtResponseCode.RESULT_OK) {
            if (response.result instanceof OrderItem) {
                orderItem = (OrderItem) response.result;
                String moneyType=orderItem.getPayCurrency();
                if("CNY".equals(moneyType.toUpperCase())){
                    OrderBusiness.getFinalPrice(mApiProxy,oid,orderItem.getPayCurrency(),PAY_CHANEL_ALIPAY,"");
                }else{
                    OrderBusiness.getFinalPrice(mApiProxy,oid,orderItem.getPayCurrency(),PAY_CHANEL_VISA,"");
                }
            }else if (response.result instanceof PayMode){
                PayMode payMode = (PayMode) response.result;
                if(isInitial){
                    renderUi(orderItem,discountItem,payMode);
                    isInitial=false;
                    mPayOrderView.displayContent();
                }else{
                    mPayOrderView.renderPriceDetailInfo(discountItem,payMode);
                }
            }
        }else {
            mPayOrderView.displayNoNetwork();
            if (!TextUtils.isEmpty(response.msg)) {
                MessageUtils.showToast(response.msg);
            }
        }
    }

    public void selectPayMethod(String channel,DiscountItem discountItem){
        if (channel.equals(ResourceUtil.getString(R.string.account_alipay))){
            channel=PAY_CHANEL_ALIPAY;
        }else if (channel.equals(ResourceUtil.getString(R.string.account_wechatpay))){
            channel=PAY_CHANEL_WXPAY;
        }else if(channel.equals(ResourceUtil.getString(R.string.account_visa))){
            channel=PAY_CHANEL_VISA;
        }else if (channel.equals(ResourceUtil.getString(R.string.account_mastercard))){
            channel=PAY_CHANEL_MASTERCARD;
        }
        if (discountItem==null){
            OrderBusiness.getFinalPrice(mApiProxy,oid,orderItem.getPayCurrency(),channel,"");
        }else{
            OrderBusiness.getFinalPrice(mApiProxy,oid,orderItem.getPayCurrency(),channel,discountItem.getCode());
        }
    }


    public void renderUi(OrderItem orderItem,DiscountItem discountItem,PayMode payMode){
        mPayOrderView.renderServicePartInfo(orderItem);
        mPayOrderView.renderCouponInfo(discountItem);
        mPayOrderView.renderPriceDetailInfo(discountItem, payMode);
        mPayOrderView.renderPayMethodInfo(orderItem);
    }

    @Override
    public void detachView() {
        mPayOrderView =null;
    }


    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        CtApiResponse response = (CtApiResponse) result.getData();
        if (ApiManager.GET_ORDER_INFO.equals(response.getApiName())) {
            handResponse(response);
        } else if (ApiManager.GET_CHARGE.equals(response.getApiName())) {
            handResponse(response);
        } else if (ApiManager.FINAL_PRICE.equals(response.getApiName())){
            handResponse(response);
        }
        return false;
    }
}
